import logging
import random
import re

from django.views import View
from django_redis import get_redis_connection
from django import http

from celery_tasks.Email.tasks import send_Email_code
from meiduo_mall.utils.response_code import RETCODE
from verifications.libs.captcha.captcha import captcha
from . import constants

# Create your views here.


class ImageCodeView(View):
    """ 图形验证码 """

    def get(self, request, uuid):
        """
        :param uuid: 通用唯一识别码 用于识别用户
        :return:
        """
        # 接受校验

        # 生成
        text, image = captcha.generate_captcha()
        # 保存
        redis_conn = get_redis_connection('verify_code')
        # redis_conn.setex('key', 'expires', 'value')
        redis_conn.setex(f'img_{uuid}', constants.IMAGE_CODE_REDIS_EXPIRES, text)
        # 响应
        return http.HttpResponse(image, content_type='image/jpg')


class EmailCodeView(View):
    """ 邮箱验证码 """

    def get(self, request):
        Email = request.GET.get('Email')
        uuid = request.GET.get('uuid')
        image_code = request.GET.get('image_code')

        # 判断参数是否齐全
        if not all([Email, uuid, image_code]):
            return http.JsonResponse({'code': RETCODE.NECESSARYPARAMERR, 'errmsg': '缺少关键参数'})
        # 判断邮箱格式
        if not re.match(r'^[A-Za-z0-9\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$', Email):
            return http.JsonResponse({'code': RETCODE.EMAILERR, 'errmsg': '请输入正确的邮箱'})


        redis_conn = get_redis_connection('verify_code')
        send_flag = redis_conn.get(f'send_flag_{Email}')
        if send_flag:
            second = redis_conn.ttl(f'send_flag_{Email}') # 剩余时间
            return http.JsonResponse({'code': RETCODE.THROTTLINGERR, 'errmsg': '发送邮件过于频繁','second': second})

        # 获取图形验证码
        image_code_server = redis_conn.get(f'img_{uuid}')
        if image_code_server is None:
            return http.JsonResponse({'code': RETCODE.IMAGECODEERR, 'errmsg': '图形验证码失效'})
        # 删除记录
        try:
            redis_conn.delete(f'img_{uuid}')
        except Exception as e:
            logging.error(e)
        image_code_server = image_code_server.decode()  # bytes转字符串
        if image_code_server.lower() != image_code.lower():
            return http.JsonResponse({'code': RETCODE.IMAGECODEERR, 'errmsg': '输入图形验证码有误'})

        Email_code = '%06d' % random.randint(0, 999999)
        # 标记
        pl = redis_conn.pipeline()
        pl.setex(f'Email_{Email}', constants.SMS_CODE_REDIS_EXPIRES, Email_code)
        pl.setex(f'send_flag_{Email}', constants.SEND_SMS_CODE_INTERVAL,1)
        pl.execute()

        # EmailCode(Email).send_Email_code(Email_code)
        send_Email_code.delay(Email, Email_code) # 异步发送邮件

        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': '发送成功'})
